package com.spider.ask120.action;

import java.io.IOException;

import org.jdiy.core.App;
import org.jdiy.core.JDiyAction;

import com.spider.ask120.webmagic.Jingyan;
import com.spider.ask120.webmagic.JingyanCatalog;
import com.wilddog.client.DataSnapshot;
import com.wilddog.client.Query;
import com.wilddog.client.ValueEventListener;
import com.wilddog.client.Wilddog;
import com.wilddog.client.WilddogError;

import us.codecraft.webmagic.Spider;

public class CatalogAction extends JDiyAction{
	App app = App.get();
	public void addJingyan(){ 
		Spider.create(new JingyanCatalog()).addUrl("http://m.120ask.com/jingyan/").thread(1).run();
		try {
			app.getResponse().getWriter().write("ok");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void getJingyanCata(){
 
		Wilddog dog = new Wilddog("https://cyqa.wilddogio.com/channel/jingyan/child/1kwmmhsksk");
		
		Query query = dog.orderByKey();
		query.addListenerForSingleValueEvent(new ValueEventListener() { 
			
			public void onDataChange(DataSnapshot snapshot) {  
				foreachSnapSort(snapshot,"");
			} 
			public void onCancelled(WilddogError arg0) {
			}
		});
	}
	
	
	public void foreachSnapSort(DataSnapshot snapshot, String cat){ 
		if(snapshot.child("child").getChildrenCount() > 0){
			Iterable<DataSnapshot> children = snapshot.child("child").getChildren();
			for (DataSnapshot childSnap : children) {
//				//System.out.println(childSnap.getKey()+""+childSnap.child("value").getValue());
				String child = snapshot.getKey().equals("jingyan")?"":snapshot.getKey();

				String cata = "";
				if(cat.isEmpty() && !child.isEmpty()){
					cata = child;
				}else if(!cat.isEmpty() && !child.isEmpty()){
					cata = cat+","+child;
				}
				foreachSnapSort(childSnap, cata);
			}
		}else{
//			//System.out.println(snapshot.getKey() +" = " + snapshot.getValue().toString());
			cat += cat.isEmpty()?""+snapshot.getKey():","+snapshot.getKey();
//			System.err.println("http://m.120ask.com/jingyan/list/"+snapshot.getKey()+".html?cat="+cat);
//			String[] cats = cat.split(",");
//			String childPath = "";
//			for(int c = 0; c < cats.length; c++){
//				if(c == cats.length - 1){
//					childPath += "/"+cats[c]+"/";
//				}else{
//					childPath += "/"+cats[c]+"/child"; 
//				}
//			}
//			System.err.println(childPath);
			Spider.create(new Jingyan())
					.addUrl("http://m.120ask.com/jingyan/list/"+snapshot.getKey()+".html?cat="+cat)
					.thread(1).run();
		}
	}
	
	
	
}
